package com.xinxing.learning.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@Configuration
public class ParameterFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper((HttpServletRequest) servletRequest);
        String body = parameterRequestWrapper.getBody();
        if (null != body && !"".equalsIgnoreCase(body)) {
            Map<String, String> map = new ObjectMapper().readValue(body, Map.class);
            parameterRequestWrapper.addParameter("_csrf", map.get("_csrf"));
        }
        filterChain.doFilter(parameterRequestWrapper, servletResponse);
    }
}
